package com.ruoyi.web.controller;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.web.controller.Service.MailService;
import com.ruoyi.web.controller.tool.RedisTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;

@Controller
@RequestMapping("/system/sendmail")
public class SendMailController {
    @Autowired
    private MailService mailService;
    @Resource
    RedisTool redisTool;

    final static String subject = "登录验证码";

    /**
     * 发送文本邮件
     *
     * @param EmailAddress
     */
    @PostMapping("/sendTextMail")
    @ResponseBody
    public AjaxResult sendTextMail(@RequestParam("EmailAddress")String EmailAddress) {


        Jedis jedis = redisTool.getJedis();
        if (jedis.exists(EmailAddress)) {
            return AjaxResult.error("请不要频繁发送验证码！");
        } else {
            int Rad = 0;
            Rad = (int) (Math.random() * 10000);
            String Reddom = String.valueOf(Rad);
            while (Reddom.length() < 6) {
                Reddom = "1" + Reddom;
            }
            String MesCode = "打死都不要说！您的验证码是" + Reddom + "，5分钟内有效！";
            mailService.sendTextMailMessage(EmailAddress, subject, MesCode);
            jedis.set(EmailAddress, Reddom);    //存储
            jedis.expire(EmailAddress, 60 * 5);  //设置时长
            return AjaxResult.success("发送成功！"+Reddom);
        }

    }

}
